package fr.jade.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;

import fr.jade.util.log.Logger;

public class StreamForwarder
extends Thread
{
	private OutputStream ostream;
	private InputStream istream;
	private String prefix;
	
	private boolean found;
	private String wantedStr;
	
	public StreamForwarder(String prefix, InputStream istream, OutputStream ostream)
	{
		this.ostream = ostream;
		this.istream = istream;
		this.prefix = prefix;
	}
	
	public void prepareWaitForString(String str)
	throws JadeException
	{
		synchronized (this) 
		{
			if (wantedStr != null)
				throw new JadeException("Only one grep at a time");
			wantedStr = str;
			found = false;
		}
	}
	
	public void waitForString()
	throws JadeException
	{
		synchronized (this)
		{
			if (!found) {
				if (wantedStr == null)
					throw new JadeException("No search prepared");
				try { wait(); } catch (InterruptedException ignored) {}
			}
		}
	}
	
	public void run()
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(istream));
		PrintStream pstream = new PrintStream(ostream);

		pstream.println(prefix + "-- begin --");
		try {
			while (true)
			{
				String next = br.readLine();
				if (next==null)	break;
				pstream.println(prefix + next);
				synchronized (this)
				{
					if (wantedStr != null && next.indexOf(wantedStr)!=-1)
					{
						found = true;
						wantedStr = null;
						notify();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		pstream.println(prefix + "--- end ---");
		synchronized (this)
		{
			if (wantedStr != null)
			{
				Logger.println("WARNING: StreamForwarder.waitForStdout never returned! Releasing thread");
				found = true;
				wantedStr = null;
				notify();
			}
		}
	}
}
